package com.buanalintas.sandals.pos.retur;

import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.formatter.DateFormatter;
import com.buanalintas.sandals.pos.entities.PosMasterItemStock;
import com.buanalintas.sandals.pos.entities.PosMasterStatus;
import com.buanalintas.sandals.pos.entities.PosTransactionItemStock;
import com.buanalintas.sandals.pos.entities.PosTransactionPurchaseOrder;
import com.buanalintas.sandals.pos.entities.PosTransactionReceipt;
import com.buanalintas.sandals.pos.entities.PosTransactionRetur;
import com.buanalintas.sandals.pos.entities.PosTransactionReturDetail;
import com.buanalintas.sandals.pos.item.Item;
import com.buanalintas.sandals.pos.returdetail.ReturDetail;
import com.buanalintas.sandals.pos.status.Status;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Retur extends Page {

    private Field returId;
    private Field returUserId;
    private Field returUnitId;
//    private Field returPurchaseOrderId;
    private Field returReceiptId;
    private Field returDate;
    private Field returNumber;
    private Field returQuantity;
    private Field returDescription;
    private Field returTimestamp;

    public Retur() {
        super();
        setTheClass(PosTransactionRetur.class);
        setPageDetail(ReturDetail.class);

        returId = new Field();
        returId.setName("returId");
        returId.setCaption("id");
        returId.setListProperties("");
        returId.setInputProperties("");
        getFields().add(returId);

        returUserId = new Field();
        returUserId.setName("returUserId");
        returUserId.setCaption("user");
        returUserId.setListProperties(" size=\"20\"");
        returUserId.setInputProperties(" size=\"20\"");
        getFields().add(returUserId);

        returUnitId = new Field();
        returUnitId.setName("returUnitId");
        returUnitId.setCaption("unit");
        returUnitId.setListProperties(" size=\"20\"");
        returUnitId.setInputProperties(" size=\"20\"");
        getFields().add(returUnitId);

//        returPurchaseOrderId = new Field();
//        returPurchaseOrderId.setName("returPurchaseOrderId");
//        returPurchaseOrderId.setCaption("purchase order");
//        returPurchaseOrderId.setListProperties(" align=\"center\" width=\"15%\" nowrap");
//        returPurchaseOrderId.setInputProperties(" size=\"20\" readonly");
//        returPurchaseOrderId.setRequired(true);
//        returPurchaseOrderId.setSelectorLoad(true);
//        returPurchaseOrderId.setSelectorCondition("t.purchaseOrderStatus='2'");
//        returPurchaseOrderId.getSelectorAction().add(new String[]{"value", "returPurchaseOrderId", "PurchaseOrderId"});
//        returPurchaseOrderId.getSelectorAction().add(new String[]{"value", "returDescription", "purchaseOrderDescription"});
//        returPurchaseOrderId.getSelectorColumns().add(new String[]{"purchaseOrderNumber", "Number", " align=\"center\" width=\"20%\" nowrap"});
//        returPurchaseOrderId.getSelectorColumns().add(new String[]{"purchaseOrderTotalQuantity", " Total Purchase Order", "align=\"right\" width=\"10%\""});
//        returPurchaseOrderId.getSelectorColumns().add(new String[]{"purchaseOrderReceived", " Received", "align=\"right\" width=\"10%\" nowrap"});
//        returPurchaseOrderId.getSelectorColumns().add(new String[]{"purchaseOrderDescription", " Description", "align=\"left\" width=\"60%\""});
//        returPurchaseOrderId.setSelectorOrder("t.purchaseOrderNumber");
//        getFields().add(returPurchaseOrderId);

        returReceiptId = new Field();
        returReceiptId.setName("returReceiptId");
        returReceiptId.setCaption("receipt");
        returReceiptId.setListProperties(" align=\"center\" width=\"15%\" nowrap");
        returReceiptId.setInputProperties(" size=\"20\" readonly");
        returReceiptId.setRequired(true);
        returReceiptId.setSelectorLoad(true);
        returReceiptId.setSelectorCondition("t.receiptKeel='1'");
        returReceiptId.getSelectorAction().add(new String[]{"value", "returReceiptId", "receiptId"});
        returReceiptId.getSelectorAction().add(new String[]{"value", "returDescription", "receiptDescription"});
        returReceiptId.getSelectorColumns().add(new String[]{"receiptNumber", "Number", " align=\"center\" width=\"20%\" nowrap"});
        returReceiptId.getSelectorColumns().add(new String[]{"receiptTotal", " Total Purchase Order", "align=\"right\" width=\"10%\""});
        returReceiptId.getSelectorColumns().add(new String[]{"receiptPurchaseOrderTotalQuantity", " Total Quantity", " align=\"center\" width=\"10%\" nowrap"});
//        returReceiptId.getSelectorColumns().add(new String[]{"receiptPurchaseOrderReceived", " Received", "align=\"right\" width=\"10%\" nowrap"});
        returReceiptId.getSelectorColumns().add(new String[]{"receiptDescription", " Description", "align=\"left\" width=\"60%\""});
        returReceiptId.setSelectorOrder("t.receiptNumber");
        getFields().add(returReceiptId);

        returDate = new Field();
        returDate.setName("returDate");
        returDate.setCaption("date");
        returDate.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        returDate.setInputProperties(" size=\"8\" readonly");
        returDate.setDefaultValue(Utility.getTimestamp());
        returDate.setRequired(true);
        getFields().add(returDate);

        returNumber = new Field();
        returNumber.setName("returNumber");
        returNumber.setCaption("number");
        returNumber.setListProperties(" align=\"center\" width=\"15%\" nowrap");
        returNumber.setInputProperties(" size=\"20\" readonly");
        returNumber.setRequired(true);
        getFields().add(returNumber);

        returQuantity = new Field();
        returQuantity.setName("returQuantity");
        returQuantity.setCaption("quantity");
        returQuantity.setListProperties(" align=\"right\" width=\"8%\" nowrap");
        returQuantity.setInputProperties(" size=\"8\"");
        returQuantity.setRequired(true);
        getFields().add(returQuantity);

        returDescription = new Field();
        returDescription.setName("returDescription");
        returDescription.setCaption("description");
        returDescription.setListProperties(" align=\"left\" width=\"55%\" nowrap");
        returDescription.setInputProperties(" cols=\"50\" rows=\"5\"");
        returDescription.setInputType(Field.INPUT_TEXT_AREA);
        returDescription.setInputCase(Field.CASE_UPPER);
        getFields().add(returDescription);

        returTimestamp = new Field();
        returTimestamp.setName("returTimestamp");
        returTimestamp.setCaption("timestamp");
        returTimestamp.setListProperties(" align=\"center\" width=\"10%\" nowrap");
        returTimestamp.setInputProperties(" size=\"12\"");
        getFields().add(returTimestamp);

        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);

        fillFields();

        getFieldsAdd().clear();
        getFieldsAdd().add(returNumber);
        getFieldsAdd().add(returDate);
//        getFieldsAdd().add(returPurchaseOrderId);
        getFieldsAdd().add(returReceiptId);
//        getFieldsAdd().add(returQuantity);
        getFieldsAdd().add(returDescription);

        getFieldsEdit().clear();
        getFieldsEdit().add(returNumber);
        getFieldsEdit().add(returDate);
//        getFieldsEdit().add(returPurchaseOrderId);
        getFieldsEdit().add(returReceiptId);
//        getFieldsEdit().add(returQuantity);
        getFieldsEdit().add(returDescription);

        getFieldsList().clear();
        getFieldsList().add(returNumber);
        getFieldsList().add(returDate);
//        getFieldsList().add(returPurchaseOrderId);
        getFieldsList().add(returReceiptId);
        getFieldsList().add(returQuantity);
        getFieldsList().add(returDescription);

        getFieldsView().clear();
        getFieldsView().add(returNumber);
        getFieldsView().add(returDate);
        getFieldsView().add(returUserId);
        getFieldsView().add(returUnitId);
//        getFieldsView().add(returPurchaseOrderId);
        getFieldsView().add(returReceiptId);
        getFieldsView().add(returQuantity);
        getFieldsView().add(returDescription);
        getFieldsView().add(returTimestamp);

        setController(new ReturController(this));
        getController().setOrder(returTimestamp);
        getController().setOrderType(Controller.ORDER_DESC);

        setExportList(getClass().getResourceAsStream("ReturList.jasper"));
        setExport(getClass().getResourceAsStream("Retur.jasper"));
    }

//    @Override
//    public String validate(Object data) {
//        HttpSession session = getRequest().getSession();
//        EntityManager em = getEntityManager();
//        PosTransactionRetur retur = (PosTransactionRetur) data;
//        Integer remaining = retur.getReturReceiptId().getReceiptPurchaseOrderReceived();
//        if (retur.getReturQuantity().compareTo(remaining) > 0) {
//            return retur.getReturReceiptId() + " " + Dictionary.getValue(this, "Too much quantity") + ", " + Dictionary.getValue(this, "total quantity receipt") + ": " + remaining + " " + Dictionary.getValue(this, "item you retur now") + ": " + retur.getReturQuantity();
//        }
//        return null;
//    }
    @Override
    public void afterInit(HttpServletRequest req, HttpServletResponse res) {
        returDate.setFormater(DateFormatter.getInstanceDate(this));
        returTimestamp.setFormater(DateFormatter.getInstanceDateTime(this));
    }

    @Override
    public void beforeAdd() {
        returNumber.setDefaultValue(generate());
    }

//    @Override
//    public void beforeList() {
//        if (!getCurrentUnit().getUnitId().equals(1)) {
//            getController().setCondition("t.requestUnitId.unitId=" + getCurrentUnit().getUnitId());
//        }
//    }
    class ReturController extends Controller {

        public ReturController(Page page) {
            super(page);
            setOrder(returTimestamp);
            setOrderType("DESC");
        }

        @Override
        public void beforeInsert(Object data, List detail) {
            PosTransactionRetur retur = (PosTransactionRetur) data;
            retur.setReturNumber(generate());
            retur.setReturUnitId(getCurrentUnit());
            retur.setReturUserId(getCurrentUser());
            retur.setReturTimestamp(Utility.getTimestamp());
            
//             for (int i = detail.size() - 1; i > 0; i--) {
//                PosTransactionReturDetail d1 = (PosTransactionReturDetail) detail.get(i);
//                for (int j = 0; j < i; j++) {
//                    PosTransactionReturDetail d2 = (PosTransactionReturDetail) detail.get(j);
//                    if (d2.getReturDetailItemId().equals(d1.getReturDetailItemId())) {
//                        d2.setReturDetailQuantity(d2.getReturDetailQuantity()+d1.getReturDetailQuantity());
//                        detail.remove(i);
//                        break;
//                    }
//                }
//            }
//            if (retur.getReturPurchaseOrderId() != null) {
//                retur.getReturPurchaseOrderId().setPurchaseOrderReturQuantity(retur.getReturQuantity());
//            }
//            if (retur.getReturReceiptId() != null) {
//                retur.getReturReceiptId().setReceiptReturQuantity(retur.getReturQuantity());
//            }
        }

        @Override
        public void afterInsert(Object data, List list) {
            EntityManager em = getEntityManager();
            PosMasterStatus statusGood = Status.getStatusGood(em);
            try {
                em.getTransaction().begin();
                PosTransactionRetur retur = (PosTransactionRetur) data;
                PosTransactionReceipt receipt = retur.getReturReceiptId();
//                PosTransactionReceiptDetail receiptDetails = (PosTransactionReceiptDetail) data;
//                PosTransactionPayment payment = (PosTransactionPayment) data;

                BigDecimal total = BigDecimal.ZERO;
                int totalQuantity = 0;
                String desc = "";
                for (Object detail : list) {
                    PosTransactionReturDetail returDetail = (PosTransactionReturDetail) detail;
                    PosMasterItemStock stock = Item.getStock(em, returDetail.getReturDetailItemId(), retur.getReturUnitId(), statusGood, returDetail.getReturDetailItemId().getItemColorId(), returDetail.getReturDetailSizeId());
                    PosTransactionItemStock itemStock = new PosTransactionItemStock();

                    itemStock.setItemStockId(Sequence.next(itemStock));
                    itemStock.setItemStockItemId(returDetail.getReturDetailItemId());
                    itemStock.setItemStockSizeId(returDetail.getReturDetailSizeId());
                    itemStock.setItemStockColorId(returDetail.getReturDetailItemId().getItemColorId());
                    itemStock.setItemStockUnitId(retur.getReturUnitId());
                    itemStock.setItemStockStatusId(statusGood);
                    itemStock.setItemStockType("4");
                    itemStock.setItemStockLast(stock.getItemStockValue());
                    itemStock.setItemStockValue(returDetail.getReturDetailQuantity());
                    itemStock.setItemStockCurrent(itemStock.getItemStockLast() - itemStock.getItemStockValue());
                    itemStock.setItemStockUserId(page.getCurrentUser());
                    itemStock.setItemStockTimestamp(Utility.getTimestamp());
                    em.persist(itemStock);

                    totalQuantity = totalQuantity + returDetail.getReturDetailQuantity();
                    total = returDetail.getReturDetailPrice().multiply(new BigDecimal(returDetail.getReturDetailQuantity()));
                    desc = desc + "Retur " + returDetail.getReturDetailItemId() + " Quantity = " + returDetail.getReturDetailQuantity()
                            + " Dengan Harga = " + returDetail.getReturDetailPrice()
                            + ". ";
                }

                receipt.setReceiptReturQuantity(totalQuantity);
                receipt.setReceiptTotal(receipt.getReceiptTotal().subtract(total));
                receipt.setReceiptDescription(desc);
                retur.setReturQuantity(totalQuantity);
                retur.setReturDescription(desc);
                receipt.getReceiptPurchaseOrderId().setPurchaseOrderReturQuantity(totalQuantity);
                receipt.getReceiptPurchaseOrderId().setPurchaseOrderReturTotal(total);
//                payment.setPaymentTotal(total);

//                List<PosTransactionPurchaseOrder> po;
//                po = em.createQuery("SELECT t FROM PosTransactionPurchaseOrder t"
//                        + " WHERE t.purchaseOrderSupplierId.supplierId="+retur.getReturReceiptId().getReceiptPurchaseOrderId().getPurchaseOrderSupplierId().getSupplierId()
//                        + " AND t.purchaseOrderStatus='2' AND t.purchaseOrderKeel='1' ORDER BY t.purchaseOrderTimestamp ASC").
//                        setHint(Persistence.REFRESH_HINT, true).getResultList();
//                System.out.println("Cek PO Dist " + po);
//                if (po != null) {
//                    for (Object poSup : po) {
//                        PosTransactionPurchaseOrder poSupplier = (PosTransactionPurchaseOrder) poSup;
//                        poSupplier.setPurchaseOrderReturQuantity(totalQuantity);
////                        poSupplier.setPurchaseOrderTotal(poSupplier.getPurchaseOrderTotal().subtract(total));
//                    }
//
//                }
                em.getTransaction().commit();
            } catch (Exception e) {
                Logger.getInstance().log(e);
                System.out.println(" ERRR :" + e);
            }
        }
//        @Override
//        public void beforeUpdate(Object data, List list, List listDelete) {
//            PosTransactionRetur retur = (PosTransactionRetur) data;
//            retur.setReturProgress("1");
//            retur.setReturProgress(Dictionary.getValue(page, "Revision") + ": " + retur.getReturRejectReason());
//        }
    }

    public String generate() {
        String unitCode = (getCurrentUnit()).getUnitCode();
        Calendar cal = Calendar.getInstance();
        String year = "" + cal.get(Calendar.YEAR);
        String month = Utility.intToRoman(cal.get(Calendar.MONTH) + 1);
        try {
            PosTransactionRetur retur = (PosTransactionRetur) getEntityManager().createQuery("SELECT t FROM PosTransactionRetur t WHERE t.returNumber LIKE '%/" + unitCode + "/RET/%/" + year + "' ORDER BY t.returTimestamp DESC").setHint(Persistence.REFRESH_HINT, true).setFirstResult(0).setMaxResults(1).getSingleResult();
            return Utility.lpad(Integer.parseInt(retur.getReturNumber().substring(0, 4)) + 1, 4, "0") + "/" + unitCode + "/RET/" + month + "/" + year;
        } catch (Exception e) {
        }
        return "0001/" + unitCode + "/RET/" + month + "/" + year;
    }

    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Retur"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();
    }
}
